﻿using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Linq;

namespace BlockchainCrypto
{
    class Address
    {
        /// <summary>
        /// Alaya由私钥生成地址
        /// </summary>
        public static void Main()
        {
            byte[] privateKey = Hex.Decode("1196cf2b491f5522565918c5432b9f864f88dd04b92045317da9ffc28ff4020b");
            X9ECParameters curve = SecNamedCurves.GetByName("secp256k1");
            //var curve = ECNamedCurveTable.GetByName("secp256k1");

            BigInteger d = new BigInteger(privateKey);
            ECPoint q = curve.G.Multiply(d); 
            //Console.WriteLine(Hex.ToHexString(q.GetEncoded()));

            // for ethereum
            // var publicKey = Hex.ToHexString(q.GetEncoded());
            var publicKey = Hex.ToHexString(q.GetEncoded())[2..];
            Console.WriteLine(publicKey);
            byte[] pkBytes = Hex.Decode(publicKey);
            var hashAlgorithm = new KeccakDigest(256);
            //byte[] input = last16BytesOfDerivedKey.ToArray();
            hashAlgorithm.BlockUpdate(pkBytes, 0, pkBytes.Length);

            byte[] result = new byte[32]; // 256 / 8 = 32
            hashAlgorithm.DoFinal(result, 0);
            var addressBytes = result.Skip(result.Length - 20).ToArray();
            //Console.WriteLine(Hex.ToHexString(publicParams.Q.GetEncoded()));

            var address = Bech32Engine.Encode("atp", addressBytes);
            Console.WriteLine(address);
        }
    }
}
